<template>
  <view class="container">
    <!-- 订单状态标签 -->
    <view class="status-tabs">
      <scroll-view scroll-x class="tabs-scroll">
        <view class="tabs-container">
          <view
            v-for="tab in orderTabs"
            :key="tab.id"
            class="tab-item"
            :class="{ active: currentTab === tab.id }"
            @tap="changeTab(tab.id)"
          >
            {{ tab.name }} ({{ getOrderCount(tab.id) }})
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 订单列表 -->
    <view v-if="filteredOrders.length > 0" class="order-list">
      <view
        v-for="order in filteredOrders"
        :key="order.id"
        class="order-card"
        @tap="goToOrderDetail(order.id)"
      >
        <view class="order-header">
          <text class="order-number">订单号：{{ order.orderNumber }}</text>
          <text class="order-status" :class="order.status">
            {{ getStatusText(order.status) }}
          </text>
        </view>

        <view class="order-items">
          <view
            v-for="item in order.items.slice(0, 2)"
            :key="item.id"
            class="order-item"
          >
            <image class="item-image" :src="item.image" mode="aspectFill" />
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-quantity">x{{ item.quantity }}</text>
            </view>
          </view>
          <text v-if="order.items.length > 2" class="more-items">
            等{{ order.items.length }}件商品
          </text>
        </view>

        <view class="order-summary">
          <view class="total-points">
            <text class="points-value">{{ order.totalPoints }}</text>
            <u-icon name="heart-fill" color="#ff6b81" size="14" />
          </view>
          <text class="order-time">{{ formatTime(order.createdAt) }}</text>
        </view>

        <view class="order-actions">
          <custom-button
            v-if="order.status === 'pending'"
            type="secondary"
            size="small"
            text="取消订单"
            @click.stop="cancelOrder(order.id)"
          />
          <custom-button
            v-if="order.status === 'pending'"
            type="primary"
            size="small"
            text="确认取餐"
            @click.stop="confirmOrder(order.id)"
          />
          <custom-button
            v-if="order.status === 'completed'"
            type="primary"
            size="small"
            text="再来一单"
            @click.stop="reorder(order.id)"
          />
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <u-empty
        mode="order"
        :text="getEmptyText()"
        icon="http://cdn.uviewui.com/uview/empty/order.png"
      />
      <custom-button
        v-if="currentTab === 'all'"
        type="primary"
        text="去点餐"
        @click="goToMenu"
      />
    </view>

    <!-- 加载更多 -->
    <view v-if="loading" class="loading-more">
      <u-loading-icon text="加载中..." />
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useOrderStore } from '@/store/modules/order'

const orderStore = useOrderStore()

// 数据
const loading = ref(false)
const currentTab = ref('all')

// 订单标签
const orderTabs = ref([
  { id: 'all', name: '全部' },
  { id: 'pending', name: '待处理' },
  { id: 'completed', name: '已完成' },
  { id: 'cancelled', name: '已取消' }
])

// 计算属性
const orders = computed(() => orderStore.orders)

const filteredOrders = computed(() => {
  if (currentTab.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => order.status === currentTab.value)
})

// 方法
const changeTab = (tabId) => {
  currentTab.value = tabId
}

const getOrderCount = (tabId) => {
  if (tabId === 'all') {
    return orders.value.length
  }
  return orders.value.filter(order => order.status === tabId).length
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) { // 1天内
    return Math.floor(diff / 3600000) + '小时前'
  } else {
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${month}月${day}日 ${hours}:${minutes}`
  }
}

const goToOrderDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/detail?id=${orderId}`
  })
}

const cancelOrder = (orderId) => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消这个订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '取消中...' })
          await orderStore.cancelOrder(orderId)
          uni.hideLoading()
          uni.showToast({
            title: '订单已取消',
            icon: 'success'
          })
        } catch (error) {
          uni.hideLoading()
          uni.showToast({
            title: '取消失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const confirmOrder = (orderId) => {
  uni.showModal({
    title: '确认取餐',
    content: '确定已取餐完成吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '确认中...' })
          await orderStore.completeOrder(orderId)
          uni.hideLoading()
          uni.showToast({
            title: '取餐完成',
            icon: 'success'
          })
        } catch (error) {
          uni.hideLoading()
          uni.showToast({
            title: '确认失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const reorder = (orderId) => {
  const order = orders.value.find(o => o.id === orderId)
  if (order) {
    // 这里可以实现一键重新下单的逻辑
    uni.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  }
}

const goToMenu = () => {
  uni.switchTab({ url: '/pages/menu/index' })
}

const getEmptyText = () => {
  const textMap = {
    all: '暂无订单',
    pending: '暂无待处理订单',
    completed: '暂无已完成订单',
    cancelled: '暂无已取消订单'
  }
  return textMap[currentTab.value] || '暂无订单'
}

const loadOrders = async () => {
  try {
    loading.value = true
    await orderStore.getOrders()
  } catch (error) {
    console.error('加载订单失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadOrders()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 1334rpx;
}

.status-tabs {
  margin-bottom: 20rpx;
  
  .tabs-scroll {
    white-space: nowrap;
    
    .tabs-container {
      display: inline-flex;
      padding: 0 10rpx;
      
      .tab-item {
        padding: 15rpx 30rpx;
        margin-right: 20rpx;
        background: #fff;
        border-radius: 30rpx;
        font-size: 26rpx;
        color: #666;
        border: 1rpx solid #e0e0e0;
        
        &.active {
          background: #ff6b81;
          color: #fff;
          border-color: #ff6b81;
}
      }
    }
  }
}

.order-list {
  margin-bottom: 20rpx;
}

.order-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .order-number {
      font-size: 24rpx;
      color: #666;
}
    
    .order-status {
      font-size: 24rpx;
      font-weight: bold;
      
      &.pending {
        color: #ff6b81;
}
      
      &.completed {
        color: #52c41a;
}
      
      &.cancelled {
        color: #999;
}
    }
  }
  
  .order-items {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .order-item {
      display: flex;
      align-items: center;
      margin-right: 20rpx;
      
      .item-image {
        width: 60rpx;
        height: 60rpx;
        border-radius: 8rpx;
        margin-right: 10rpx;
}
      
      .item-info {
        .item-name {
          font-size: 24rpx;
          color: #333;
          display: block;
}
        
        .item-quantity {
          font-size: 20rpx;
          color: #666;
}
      }
    }
    
    .more-items {
      font-size: 24rpx;
      color: #999;
}
  }
  
  .order-summary {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .total-points {
      display: flex;
      align-items: center;
      
      .points-value {
        font-size: 28rpx;
        font-weight: bold;
        color: #ff6b81;
        margin-right: 4rpx;
}
    }
    
    .order-time {
      font-size: 24rpx;
      color: #999;
}
  }
  
  .order-actions {
    display: flex;
    justify-content: flex-end;
     margin-right: 20rpx; &:last-child { margin-right: 0; }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-more {
  padding: 30rpx;
  text-align: center;
}
</style>